package com.lxmes.common.utils;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpClientUnit {
    //添加日志
    private static Logger logger = LoggerFactory.getLogger(HttpClientUnit.class);

    public static String doPostXml(Object obj)  {
        String retStr = "";
        if (obj == null) {
            return "";
        }
        Class<?> clazz = obj.getClass(); 
        // 获取当前类的所有字段
        Field[] fields = clazz.getDeclaredFields();
        retStr += "<root xmlns:rs=\"http://www.example.com/rss\" xmlns:z=\"http://www.example.com/z\"> ";
        retStr += "<rs:data>";
        retStr+="<z:row ";
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                String fieldName = field.getName();
                Object fieldValue = field.get(obj);
                retStr+=fieldName+"=\""+fieldValue+"\" ";
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        retStr += "/>";
        retStr += "</rs:data>";
        retStr += "</root>";

        return retStr;
    }

    public static String doPostXmlList(List<Object> objectList)  {
        String retStr = "";
        if (objectList == null || objectList.isEmpty()) {
            return "";
        }
        retStr += "<root xmlns:rs=\"http://www.example.com/rss\" xmlns:z=\"http://www.example.com/z\"> ";
        retStr += "<rs:data>";

        for (Object obj : objectList){
            Class<?> clazz = obj.getClass();
            // 获取当前类的所有字段
            Field[] fields = clazz.getDeclaredFields();
            retStr+="<z:row ";
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    String fieldName = field.getName();
                    Object fieldValue = field.get(obj);
                    retStr+=fieldName+"=\""+fieldValue+"\" ";
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            retStr += "/>";
        }
        retStr += "</rs:data>";
        retStr += "</root>";

        return retStr;
    }

    /**
     * 从XML字符串中提取Success和errMsg的值
     *
     * @param xmlStr XML格式的字符串
     * @return 包含Success和errMsg值的Map
     */
    public static Map<String, String> extractSuccessAndErrMsg(String xmlStr) {
        Map<String, String> result = new HashMap<>();

        // 正则表达式，用于匹配Success和errMsg的值
        Pattern pattern = Pattern.compile("Success=\"([^\"]*)\".*errMsg=\"([^\"]*)\"");
        Matcher matcher = pattern.matcher(xmlStr);

        if (matcher.find()) {
            result.put("Success", matcher.group(1));
            result.put("errMsg", matcher.group(2));
        }

        return result;
    }

    /**
     * webServiceXml 对接U8接口
     * @param object head头数据
     * @param bodyList body体数据
     * @param login 登录账号
     * @param url 接口地址
     * @return Map<String, String>
     */
    public static Map<String, String> webServiceXml(Object object,  List<Object> bodyList, String login,String url) {
        Map<String, String> StringMap = new HashMap<>();
        String dom = doPostXml(object);
        String body = doPostXmlList(bodyList);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建HttpPost实例
            HttpPost httpPost = new HttpPost(url);
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            // 设置请求参数 创建参数列表
            List<BasicNameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("login", login));
            params.add(new BasicNameValuePair("DomHead", dom));
            params.add(new BasicNameValuePair("DomBody", body));
            params.add(new BasicNameValuePair("bCheck", "false"));
            params.add(new BasicNameValuePair("bBeforCheckStock", "false"));
            params.add(new BasicNameValuePair("bIsRedVouch", "false"));
            // 将参数列表转换为请求体
            StringEntity requestEntity = new UrlEncodedFormEntity(params, "UTF-8");
            httpPost.setEntity(requestEntity);
            // 发送POST请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                // 检查响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    // 获取响应体作为字符串
                    String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                    StringMap = HttpClientUnit.extractSuccessAndErrMsg(result);
                } else {
                    System.err.println("Error: " + response.getStatusLine());
                }
            } finally {
                // 关闭响应
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭HttpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return StringMap;
    }




    /**
     * javaBean转换StringXML
     * @param object
     * @return
     */
    public static String convertToXml(Object object) {
        try {
            // 获取对象的类
            Class<?> clazz = object.getClass();

            // 创建 JAXBContext 实例
            JAXBContext context = JAXBContext.newInstance(clazz);

            // 创建 Marshaller 实例
            Marshaller marshaller = context.createMarshaller();

            // 设置输出格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // 将对象转换为 XML 字符串
            StringWriter stringWriter = new StringWriter();
            marshaller.marshal(object, stringWriter);

            String xml = stringWriter.toString();
            // 去掉 XML 声明
           if (xml.startsWith("<?xml")) {
           xml = xml.substring(xml.indexOf("?>") + 2).trim();
             }
              return xml;
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }



}
